Namespace Result
    Public Class FixedColumnRsWriter
        Inherits Result.RsWriter
        Public WriteHeader As Boolean = True
        Public Delimiter As String = " "

        Public ColumnLengths() As Integer = New Integer() {}
        Public DefaultColumnLength As Integer = 10
        Public Encoding As System.Text.Encoding = System.Text.Encoding.Default
        Public FinalLine As Boolean = True

        Private Writer As IO.StreamWriter

        Public Sub New(ByVal Source As ADODB.Recordset, ByVal Target As String)
            MyBase.New(Source, Target)
        End Sub

        Public Overrides Function Execute() As Long
            Dim OriginalColumnLenghtsCount As Integer = ColumnLengths.Length
            Dim RsFieldsCount As Integer = Source.Fields.Count
            If RsFieldsCount > OriginalColumnLenghtsCount Then
                ReDim Preserve ColumnLengths(RsFieldsCount - 1)
                For i As Integer = OriginalColumnLenghtsCount To RsFieldsCount - 1
                    ColumnLengths(i) = DefaultColumnLength
                Next
            End If

            Writer = FileIO.FileSystem.OpenTextFileWriter(Target, False, Encoding)
            If WriteHeader Then DoWriteHeader()
            Return DoWriteValues()
        End Function

        Private Sub DoWriteHeader()
            Dim ColumnIndex As Integer = -1
            Dim ColumnLength As Integer
            For Each f As ADODB.Field In Source.Fields
                ColumnIndex = ColumnIndex + 1
                ColumnLength = ColumnLengths(ColumnIndex)
                If ColumnIndex > 0 Then Writer.Write(Delimiter)
                Writer.Write(f.Name.PadRight(ColumnLength).Substring(0, ColumnLength))
            Next
        End Sub

        Private Function DoWriteValues() As Long
            Dim ShouldWriteLine As Boolean = WriteHeader
            Dim ColumnIndex As Integer = -1
            Dim ColumnLength As Integer
            Dim ValueString As String

            Dim LineCount As Long = 0

            While Not Source.EOF
                If ShouldWriteLine Then Writer.WriteLine()
                ShouldWriteLine = True
                LineCount += 1
                ColumnIndex = -1
                For Each f As ADODB.Field In Source.Fields
                    ColumnIndex = ColumnIndex + 1
                    ColumnLength = ColumnLengths(ColumnIndex)
                    If ColumnIndex > 0 Then Writer.Write(Delimiter)
                    ValueString = FormattedValueString(f)
                    Writer.Write(ValueString.PadLeft(ColumnLength).Substring(0, ColumnLength))
                Next
                Source.MoveNext()
                Threading.Thread.Sleep(1)
            End While
            If FinalLine Then Writer.WriteLine()
            Writer.Close()
            Return LineCount
        End Function
    End Class
End Namespace
